/*
 * Copyright 2017 Xiaomi, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.zkmonitor.util;

import com.zkmonitor.common.Jurisdiction;
import com.zkmonitor.common.UserHolder;
import com.zkmonitor.exception.ShepherException;
import com.zkmonitor.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by weichuyang on 16-7-14.
 */
@Component
public class AuthStrategy {

    private static final Logger logger = LoggerFactory.getLogger(AuthStrategy.class);
    private static final Map<Integer, Pattern> URL_PATTERNS = new HashMap<>();
    private static final Map<Jurisdiction, String> AUTH_METHOD_MAPPING = new EnumMap<>(Jurisdiction.class);

    private static final int CLUSTERS_PATTERNS = 1;

    static {
        URL_PATTERNS.put(CLUSTERS_PATTERNS, Pattern.compile("^/clusters/(\\S+)/nodes"));

        AUTH_METHOD_MAPPING.put(Jurisdiction.SUPER_ADMIN, "isAdmin");
    }

   
    @Autowired
    private UserHolder userHolder;

    public boolean validate(HttpServletRequest request, Jurisdiction jurisdiction) throws ShepherException {
        boolean hasAuth;
        String authMethodName = AUTH_METHOD_MAPPING.get(jurisdiction);
        try {
            Method method = this.getClass().getDeclaredMethod(authMethodName, HttpServletRequest.class);
            hasAuth = (boolean) method.invoke(this, request);
        } catch (Exception e) {
            logger.error("Permission validation exception", e);
            throw ShepherException.createNoAuthorizationException();
        }

        return hasAuth;
    }

    public boolean isAdmin() throws ShepherException {
        User user = userHolder.getUser();
        
        return (user != null && user.getRole().equals(User.ROLE_ADMIN) );
    }

    private boolean isAdmin(HttpServletRequest request) throws ShepherException {
        return isAdmin();
    }

   

}
